/**
 * Created by henian.xu on 2017/7/17.
 * axios 配置
 */

import Vue from 'vue';
import Router from '@/router';
import Axios from 'axios';
import Config from './config';
import Qs from 'qs';

class Api {
    constructor() {
        this.createGlobalInterceptor();
    }

    /**
     * 创建全局拦截器
     */
    createGlobalInterceptor() {
        // 请求拦截
        this.addRequestInterceptor((params) => {
            return params;
        }, (_error) => {
        });
        // 响应拦截
        this.addResponseInterceptor((result) => {
            return result;
        }, (_error) => {
            const status = _error.response.status;
            switch (status) {
                case 401:
                    console.error('请登录系统!');
                    Vue.prototype.$alert('登录超时!', {
                        confirmButtonText: '确定',
                        callback: action => {
                            Router.push('/');
                        },
                    });
                    break;
                case 403:
                    Vue.prototype.$message.error('无权限访问系统模块！');
                    break;
                case 500:
                    console.error(_error.response.data);
                    // TODO:需要提供好的界面展现  Router.push('/500')
                    break;
                default:
                    break;
            }
        });
    }

    /**
     * 授权 token
     * @param token
     */
    auth(token) {
        Config.headers['token'] = token;
    }

    /**
     * 错误反馈
     */
    feedbackError(error) {
        // TODO 取不到请求 then 方法里的错误
        console.log('error', error);
    }

    /**
     * 添加请求拦截器
     * @param fn
     * @param error
     * @returns {number}
     */
    addRequestInterceptor(fn, error = () => {}) {
        return Axios.interceptors.request.use(fn, (_error) => {
            error(_error);
            this.feedbackError(_error);
            return Promise.reject(_error);
        });
    }

    /**
     * 删除请求拦截器
     * @param interceptors
     */
    removeRequestInterceptor(interceptors) {
        Axios.interceptors.request.eject(interceptors);
    }

    /**
     * 添加响应拦截器
     * @param fn
     * @param error
     * @returns {number}
     */
    addResponseInterceptor(fn, error = () => {}) {
        return Axios.interceptors.response.use(fn, (_error) => {
            error(_error);
            this.feedbackError(_error);
            return Promise.reject(_error);
        });
    }

    /**
     * 删除响应拦截器
     * @param interceptors
     */
    removeResponseInterceptor(interceptors) {
        Axios.interceptors.response.eject(interceptors);
    }

    /**
     * 创建取消令牌
     */
    createCancelToken() {
        const cancelToken = Axios.CancelToken;
        return cancelToken.source();
    }

    /**
     * get 请求
     * @param url
     * @param params
     * @returns {AxiosPromise}
     */
    get(url, params = {}) {
        return Axios.get(url, {...Config, params});
    }

    /**
     * post 请求
     * @param url
     * @param params
     * @returns {AxiosPromise}
     */
    post(url, params = {}) {
        return Axios.post(url, params, Config);
    }

    /**
     * 暂时不懂用来干嘛
     * @param url
     * @param params
     * @returns {AxiosPromise}
     */
    delete(url, params = {}) {
        let data = '';
        for (const id of params.ids) {
            data += Qs.stringify({ids: id}) + '&';
        }
        return Axios.post(url, data);
    }

    /**
     * url 跳转
     * @param url
     * @param params
     */
    export(url, params = {}) {
        // const strParams = Qs.stringify(params, {
        //     arrayFormat: 'repeat',
        //     serializeDate: d => d.getTime(),
        // })
        // url.indexOf('?') > 0 ? url = url + '&' + strParams : url = url + '?' + strParams
        // window.location.href = url
        Router.push({
            path: url,
            query: params,
        });
    }
}

export default new Api();
